/**
 * 全局加载状态管理器
 * 统一管理应用中的各种加载状态
 */

// 加载状态存储
const loadingStates = new Map()

// 加载状态监听器
const listeners = new Set()

/**
 * 加载状态管理器
 */
export class LoadingManager {
  /**
   * 开始加载
   * @param {string} key - 加载状态的唯一标识
   * @param {Object} options - 加载选项
   * @param {string} options.message - 加载提示消息
   * @param {boolean} options.showSpinner - 是否显示加载动画
   * @param {number} options.timeout - 超时时间（毫秒）
   */
  static startLoading(key, options = {}) {
    const loadingState = {
      key,
      message: options.message || '加载中...',
      showSpinner: options.showSpinner !== false,
      startTime: Date.now(),
      timeout: options.timeout || 30000,
      timer: null
    }
    
    // 设置超时处理
    if (loadingState.timeout > 0) {
      loadingState.timer = setTimeout(() => {
        console.warn(`⏰ 加载超时: ${key}`)
        this.stopLoading(key, { timeout: true })
      }, loadingState.timeout)
    }
    
    loadingStates.set(key, loadingState)
    this.notifyListeners()
    
    console.log(`🔄 开始加载: ${key}`, options.message)
    
    return key
  }
  
  /**
   * 停止加载
   * @param {string} key - 加载状态的唯一标识
   * @param {Object} result - 加载结果
   */
  static stopLoading(key, result = {}) {
    const loadingState = loadingStates.get(key)
    
    if (!loadingState) {
      console.warn(`⚠️ 尝试停止不存在的加载状态: ${key}`)
      return
    }
    
    // 清除超时定时器
    if (loadingState.timer) {
      clearTimeout(loadingState.timer)
    }
    
    // 计算加载时长
    const duration = Date.now() - loadingState.startTime
    
    console.log(`✅ 停止加载: ${key} (耗时 ${duration}ms)`, result)
    
    loadingStates.delete(key)
    this.notifyListeners()
  }
  
  /**
   * 检查是否正在加载
   * @param {string} key - 加载状态的唯一标识
   * @returns {boolean}
   */
  static isLoading(key) {
    return loadingStates.has(key)
  }
  
  /**
   * 获取加载状态详情
   * @param {string} key - 加载状态的唯一标识
   * @returns {Object|null}
   */
  static getLoadingState(key) {
    return loadingStates.get(key) || null
  }
  
  /**
   * 获取所有加载状态
   * @returns {Map}
   */
  static getAllLoadingStates() {
    return new Map(loadingStates)
  }
  
  /**
   * 检查是否有任何加载中的状态
   * @returns {boolean}
   */
  static hasAnyLoading() {
    return loadingStates.size > 0
  }
  
  /**
   * 清除所有加载状态
   */
  static clearAll() {
    // 清除所有定时器
    loadingStates.forEach(state => {
      if (state.timer) {
        clearTimeout(state.timer)
      }
    })
    
    loadingStates.clear()
    this.notifyListeners()
    
    console.log('🗑️ 已清除所有加载状态')
  }
  
  /**
   * 清除特定前缀的加载状态
   * @param {string} prefix - 前缀字符串
   */
  static clearByPrefix(prefix) {
    const keysToDelete = []
    
    loadingStates.forEach((state, key) => {
      if (key.startsWith(prefix)) {
        if (state.timer) {
          clearTimeout(state.timer)
        }
        keysToDelete.push(key)
      }
    })
    
    keysToDelete.forEach(key => loadingStates.delete(key))
    this.notifyListeners()
    
    console.log(`🗑️ 已清除前缀为 "${prefix}" 的加载状态 (${keysToDelete.length} 个)`)
  }
  
  /**
   * 添加加载状态监听器
   * @param {Function} listener - 监听器函数
   * @returns {Function} 取消监听的函数
   */
  static addListener(listener) {
    listeners.add(listener)
    
    // 返回取消监听的函数
    return () => {
      listeners.delete(listener)
    }
  }
  
  /**
   * 通知所有监听器
   */
  static notifyListeners() {
    const states = this.getAllLoadingStates()
    listeners.forEach(listener => {
      try {
        listener(states)
      } catch (error) {
        console.error('❌ 加载状态监听器错误:', error)
      }
    })
  }
  
  /**
   * 包装异步函数，自动管理加载状态
   * @param {string} key - 加载状态标识
   * @param {Function} asyncFn - 异步函数
   * @param {Object} options - 加载选项
   * @returns {Function} 包装后的函数
   */
  static wrap(key, asyncFn, options = {}) {
    return async (...args) => {
      this.startLoading(key, options)
      
      try {
        const result = await asyncFn(...args)
        this.stopLoading(key, { success: true })
        return result
      } catch (error) {
        this.stopLoading(key, { success: false, error })
        throw error
      }
    }
  }
  
  /**
   * Promise包装器，自动管理加载状态
   * @param {string} key - 加载状态标识
   * @param {Promise} promise - Promise对象
   * @param {Object} options - 加载选项
   * @returns {Promise}
   */
  static async wrapPromise(key, promise, options = {}) {
    this.startLoading(key, options)
    
    try {
      const result = await promise
      this.stopLoading(key, { success: true })
      return result
    } catch (error) {
      this.stopLoading(key, { success: false, error })
      throw error
    }
  }
  
  /**
   * 批量包装多个Promise，统一管理加载状态
   * @param {string} key - 加载状态标识
   * @param {Array<Promise>} promises - Promise数组
   * @param {Object} options - 加载选项
   * @returns {Promise}
   */
  static async wrapAll(key, promises, options = {}) {
    this.startLoading(key, options)
    
    try {
      const results = await Promise.all(promises)
      this.stopLoading(key, { success: true })
      return results
    } catch (error) {
      this.stopLoading(key, { success: false, error })
      throw error
    }
  }
  
  /**
   * 获取加载统计信息
   * @returns {Object}
   */
  static getStats() {
    const states = Array.from(loadingStates.values())
    const now = Date.now()
    
    return {
      total: states.length,
      longestDuration: states.length > 0 
        ? Math.max(...states.map(s => now - s.startTime))
        : 0,
      averageDuration: states.length > 0
        ? states.reduce((sum, s) => sum + (now - s.startTime), 0) / states.length
        : 0,
      keys: Array.from(loadingStates.keys())
    }
  }
}

/**
 * 常用加载状态键
 */
export const LOADING_KEYS = {
  // 路由加载
  ROUTE_LOADING: 'route:loading',
  
  // 用户相关
  USER_LOGIN: 'user:login',
  USER_LOGOUT: 'user:logout',
  USER_PROFILE: 'user:profile',
  USER_LIST: 'user:list',
  
  // 工单相关
  TICKET_LIST: 'ticket:list',
  TICKET_DETAIL: 'ticket:detail',
  TICKET_CREATE: 'ticket:create',
  TICKET_UPDATE: 'ticket:update',
  TICKET_DELETE: 'ticket:delete',
  
  // 权限相关
  PERMISSION_CHECK: 'permission:check',
  PERMISSION_REQUEST: 'permission:request',
  
  // 数据加载
  DATA_LOADING: 'data:loading',
  DATA_SAVING: 'data:saving',
  DATA_DELETING: 'data:deleting',
  
  // 文件操作
  FILE_UPLOAD: 'file:upload',
  FILE_DOWNLOAD: 'file:download',
  
  // 其他
  API_REQUEST: 'api:request',
  GLOBAL_LOADING: 'global:loading'
}

// 默认导出
export default LoadingManager

// Vue 3 Composition API 支持
export function useLoading(key, options = {}) {
  if (typeof window === 'undefined') {
    // SSR环境
    return {
      start: () => {},
      stop: () => {},
      isLoading: () => false
    }
  }
  
  const start = () => LoadingManager.startLoading(key, options)
  const stop = (result) => LoadingManager.stopLoading(key, result)
  const isLoading = () => LoadingManager.isLoading(key)
  
  // 组件卸载时清理
  if (typeof require !== 'undefined') {
    try {
      const { onUnmounted } = require('vue')
      onUnmounted(() => {
        if (isLoading()) {
          stop({ unmounted: true })
        }
      })
    } catch (e) {
      // Vue not available
    }
  }
  
  return {
    start,
    stop,
    isLoading
  }
}

